﻿using Auth.Api.Data;
using Auth.Api.Dtos;
using Auth.Api.Helpers;
using Auth.Api.Models;
using Microsoft.AspNetCore.Mvc;

namespace Auth.Api.Controllers
{

    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {

        private readonly IUserRepository _userRepository;
        private readonly JwtHelper _jwtHelper;

        public AuthController(IUserRepository userRepository, JwtHelper jwtHelper)
        {
            _userRepository = userRepository;
            _jwtHelper = jwtHelper;
        }


        [HttpPost("register")]
        public IActionResult Register(RegisterDto dto)
        {

            var user = new User
            {
                Name = dto.Name,
                Email = dto.Email,
                // 加密存储
                Password = BCrypt.Net.BCrypt.HashPassword(dto.Password)
            };


            var result = _userRepository.CreateUser(user);

            return Created("Success", result);
        }



        [HttpPost("login")]
        public IActionResult Login(LoginDto dto)
        {
            var user = _userRepository.GetUserByEmail(dto.Email);
            if (user == null)
            {
                return NotFound("User not found");
            }
            if (!BCrypt.Net.BCrypt.Verify(dto.Password, user.Password))
            {
                return Unauthorized("Invalid password");
            }



            // 生成 JWT

            var token = _jwtHelper.Generate(user.Id);


            // Response.Headers.Add("Authorization", token);

            // 放在 Cookie 中适合传统web程序
            /*Response.Cookies.Append("jwt", token, new CookieOptions
            { HttpOnly = true });*/

            return Ok(new
            {
                jwt = token,
            });
        }

        [HttpGet("user")]
        public IActionResult GetUser()
        {


            try
            {
                // 从header中获取 JWT
                if (!Request.Headers.TryGetValue("Authorization", out var authHeader))
                    return Unauthorized("Missing Authorization header");

                string requestJwt = authHeader.ToString().Replace("Bearer ", "");


                //var  = Request.Cookies["jwt"];

                if (string.IsNullOrEmpty(requestJwt))
                {
                    throw new UnauthorizedAccessException("JWT is missing");
                }

                var jwtSecurityToken = _jwtHelper.Verify(requestJwt);


                // 解析 JWT
                var userId = int.Parse(jwtSecurityToken.Issuer);


                var user = _userRepository.GetUserById(userId);

                return Ok(user);
            }
            catch (Exception)
            {

                return Unauthorized("Unauthorized");
                // throw new UnauthorizedAccessException("" + e.Message);
            }
        }



        [HttpPost("logout")]
        public IActionResult Logout()
        {

            //JWT 是无状态的，默认无法直接“作废”一个已签发的 Token

            /*
             *短期 Token + Refresh Token（推荐）
            Access Token：设置较短有效期（如 15-30 分钟），即使不主动注销也会很快失效。

            Refresh Token：存储在后端数据库或缓存，用户注销时删除它，阻止续签。
             *
             */
            // 清除 Cookie
            // Response.Cookies.Delete("jwt");
            return Ok("Logout success");
        }



    }
}
